package com.ztesoft.huangfu.learning.springboot.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.ztesoft.huangfu.learning.springboot.es.document.StudentDoc;
import com.ztesoft.huangfu.learning.springboot.es.repository.StudentDocRepository;
import com.ztesoft.huangfu.learning.springboot.es.service.EsSearchServiceBase;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/12/20
 * Time: 14:09
 * Version: 1.0
 * Description: 通过Repository简单的增删改查
 **/
@Service
public class EsSearchServiceBaseImpl implements EsSearchServiceBase<StudentDoc> {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private StudentDocRepository studentDocRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public void save(List<StudentDoc> data) {
        studentDocRepository.saveAll(data);
        log.info("保存索引：" + JSON.toJSONString(data));
    }

    @Override
    public void delete(String id) {
        studentDocRepository.deleteById(id);
        log.info("删除索引：" + id);
    }

    @Override
    public void deleteAll() {
        studentDocRepository.deleteAll();
        log.info("删除所有索引！");
    }

    @Override
    public StudentDoc getById(String id) {
        return studentDocRepository.findById(id).get();
    }

    @Override
    public List<StudentDoc> getAll() {
        List<StudentDoc> list = new ArrayList<>();
        studentDocRepository.findAll().forEach(new Consumer<StudentDoc>() {
            @Override
            public void accept(StudentDoc studentDoc) {
                list.add(studentDoc);
            }
        });
        // 或者用lambda表达式
//        studentDocRepository.findAll().forEach(list::add);
        log.info("获取所有索引：" + JSON.toJSONString(list));
        return list;
    }

    @Override
    public void deleteByCondition(String condition) {

        //解析condition，重组查询条件
        DeleteQuery deleteQuery = new DeleteQuery();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("age", "38"));
        deleteQuery.setQuery(queryBuilder);
        elasticsearchTemplate.delete(deleteQuery);
    }
}
